package client.XMLLoaders;

import java.awt.Rectangle;
import java.util.ArrayList;

import org.xml.sax.Attributes;

import client.Area;
import client.Building;
import client.GraphicsLoader;
import client.Obstacle;
import client.SAXReader;
import client.World;

public class LevelLoader extends SAXReader {

	private World world;
	private Area currentArea;
	private Building currentBuilding;
	private Obstacle currentObstacle;
	private Rectangle currentBounds;

	public LevelLoader(String filePath, World world) {
		this.world = world;
		super.start(filePath);
	}

	public void startElement(String uri, String name, String qName,
			Attributes atts) {
		if (qName.equals("level")) {
			currentArea = new Area();
			currentArea.setId(Integer.parseInt(atts.getValue("id")));
		} else if(qName.equals("building")) {
			currentBuilding = new Building();
		} else if(qName.equals("obstacle")) {
			currentObstacle = new Obstacle();
			currentBounds = new Rectangle();
		}
	}

	public void endElement(String uri, String name, String qName) {
		if (qName.equals("background")) {
			currentArea.loadBackground(currentData);
		} else if (qName.equals("xCoord")) {
			currentArea.setWorldX(Integer.parseInt(currentData));
		} else if (qName.equals("yCoord")) {
			currentArea.setWorldY(Integer.parseInt(currentData));
		} else if (qName.equals("buildingType")) {
			currentBuilding.setType(currentData);
			//currentArea.strength = Integer.parseInt(currentData);
		} else if (qName.equals("buildingX")) {
			currentBuilding.setX(Integer.parseInt(currentData));
		} else if (qName.equals("buildingY")) {
			currentBuilding.setY(Integer.parseInt(currentData));
		} else if (qName.equals("obType")) {
			currentObstacle.setImage( GraphicsLoader.loadImage("obstacles\\"+currentData));
		} else if (qName.equals("ox")) {
			currentBounds.x = Integer.parseInt(currentData);
		} else if (qName.equals("oy")) {
			currentBounds.y = Integer.parseInt(currentData);
		} else if (qName.equals("width")) {
			currentBounds.width = Integer.parseInt(currentData);
		} else if (qName.equals("height")) {
			currentBounds.height = Integer.parseInt(currentData);
			currentObstacle.setBoundingRect(currentBounds);
			currentArea.addObstacle(currentObstacle);
		} else if (qName.equals("level")) {
			world.addArea(currentArea);
		}
	}

	public void characters(char ch[], int start, int length) {
		super.characters(ch, start, length);
	}
}
